<template>
  <el-card class="m-20" shadow="hover">
    <el-form :inline="true" label-width="100px" class="mt-10">
      <el-form-item label="一级分类">
        <el-select placeholder="请选择一级分类" v-model="category1Id">
          <el-option
            v-for="category1 in category1List"
            :label="category1.name"
            :value="category1.id"
            :key="category1.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select placeholder="请选择二级分类" v-model="category2Id">
          <el-option
            v-for="category2 in category2List"
            :label="category2.name"
            :value="category2.id"
            :key="category2.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select placeholder="请选择三级分类" v-model="category3Id">
          <el-option
            v-for="category3 in category3List"
            :label="category3.name"
            :value="category3.id"
            :key="category3.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import {
  getCategory1List,
  getCategory2List,
  getCategory3List,
} from "@/api/category";
export default {
  name: "Category",
  data() {
    return {
      category1List: [],
      category2List: [],
      category3List: [],
      category1Id: undefined,
      category2Id: undefined,
      category3Id: undefined,
    };
  },
  async mounted() {
    const res = await getCategory1List();
    this.category1List = res.data;
  },
  methods: {},
  watch: {
    category1Id: async function (newVal) {
      const res = await getCategory2List(newVal);
      // console.log(res);
      this.category2List = res.data;
      this.category2Id = undefined;
      this.category3Id = undefined;
      this.$store.dispatch("category/getCategory1Id", newVal);
    },
    category2Id: async function (newVal) {
      if (newVal === undefined) {
        return;
      }
      const res = await getCategory3List(newVal);
      // console.log(res);
      this.category3List = res.data;
      this.category3Id = undefined;
    },
    category3Id: function (newVal) {
      this.$store.dispatch("category/getCategory3Id", newVal);
    },
  },
};
</script>

<style scoped></style>
